//
//  HZJRefreshControl.swift
//  WeiBo
//
//  Created by 陈贵 on 15/9/18.
//  Copyright © 2015年 hzj. All rights reserved.
//

import UIKit
//刷新的临界值
private let HZJMARKPOINT: CGFloat = -60


class HZJRefreshControl: UIRefreshControl {
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopBackAnimation()
    }
    
    override init() {
        super.init()
        setUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init()
        setUI()
        
    }
    
    private func setUI(){
        tintColor = UIColor.whiteColor()
        addSubview(refreshView)
        
        //约束
        refreshView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: NSLayoutAttribute.Width , relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: refreshView.bounds.width))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: NSLayoutAttribute.Height , relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: refreshView.bounds.height))
        
        //监听
        self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
    }

    //销毁监听
    deinit{
        removeObserver(self, forKeyPath: "frame", context: nil)
    }
    
    //监听事件
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if refreshing {
            
            refreshView.startBackAnimation()
        }
        
        if frame.origin.y > HZJMARKPOINT && !refreshView.isChange {
            refreshView.isChange = true
        }else if frame.origin.y <= HZJMARKPOINT && refreshView.isChange {
            refreshView.isChange = false
            //开始刷新
            print("OK")
        }
    }
    
    //懒加载
    private lazy var refreshView = RefreshView.loadTheXib()

}
//自定义刷新控件
class RefreshView:UIView {
    //方向图标
    @IBOutlet weak var directionView: UIImageView!
    //旋转图标
    @IBOutlet weak var revolveView: UIImageView!
    //表层视图
    @IBOutlet weak var topView: UIView!
    
   private var isChange = true{
        didSet{
            loadTheAnimation()
        }
    }
    
   class func loadTheXib()->RefreshView{
        return NSBundle.mainBundle().loadNibNamed("HZJREfreshView", owner: nil, options: nil).last! as! RefreshView
    }
    
    private func loadTheAnimation(){
        //旋转角度
        var angle:CGFloat = CGFloat(M_PI)
        angle += isChange ? 0.01 : -0.01
        UIView.animateWithDuration(0.5) { //() -> Void in
            self.directionView.transform = CGAffineTransformRotate(self.directionView.transform, angle)
        }
    }
    
    private func startBackAnimation(){
        
        
        //防止图标越转越快
        let animKey = "animKey"
        if revolveView.layer.animationForKey(animKey) != nil {
            return
        }
        topView.hidden = true

        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.duration = 1
        anim.repeatCount = MAXFLOAT
//        anim.removedOnCompletion = false
        revolveView.layer.addAnimation(anim, forKey: "animKey")
    }
    ///移除动画
    private func stopBackAnimation(){
        topView.hidden = false
        revolveView.layer.removeAllAnimations()
    }
    
    
    
}
